
/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/*
 *版权所有2002-2019原作者。
 *
 *根据Apache许可证2.0版许可（“许可证”）；
 *除非符合许可证的规定，否则您不得使用此文件。
 *您可以在以下网址获取许可证副本：
 *
 *https://www.apache.org/licenses/LICENSE-2.0
 *
 *除非适用法律要求或书面同意，软件
 *根据许可证进行的分发是在“按原样”的基础上进行的，
 *无任何明示或暗示的保证或条件。
 *有关管理权限的特定语言，请参阅许可证和
 *许可证下的限制。
 */

package org.springframework.jmx.support;

import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.jmx.MBeanServerNotFoundException;
import org.springframework.lang.Nullable;

/**
 * {@link FactoryBean} that obtains a {@link javax.management.MBeanServer} reference
 * through the standard JMX 1.2 {@link javax.management.MBeanServerFactory}
 * API.
 *
 * <p>Exposes the {@code MBeanServer} for bean references.
 *
 * <p>By default, {@code MBeanServerFactoryBean} will always create
 * a new {@code MBeanServer} even if one is already running. To have
 * the {@code MBeanServerFactoryBean} attempt to locate a running
 * {@code MBeanServer} first, set the value of the
 * "locateExistingServerIfPossible" property to "true".
 *
 * @author Rob Harrop
 * @author Juergen Hoeller
 * @since 1.2
 * @see #setLocateExistingServerIfPossible
 * @see #locateMBeanServer
 * @see javax.management.MBeanServer
 * @see javax.management.MBeanServerFactory#findMBeanServer
 * @see javax.management.MBeanServerFactory#createMBeanServer
 * @see javax.management.MBeanServerFactory#newMBeanServer
 * @see MBeanServerConnectionFactoryBean
 * @see ConnectorServerFactoryBean
 */
/**
 *｛@link FactoryBean｝，它获得｛@linkjavax.management.MBeanServer｝引用
 *通过标准JMX 1.2｛@link javax.management.MBeanServerFactory｝
 *API。
 *
 *＜p＞为bean引用公开｛@code MBeanServer｝。
 *
 *＜p＞默认情况下，｛@code MBeanServerFactoryBean｝将始终创建
 *一个新的{@code MBeanServer}，即使它已经在运行。拥有
 *｛@code MBeanServerFactoryBean｝尝试定位正在运行的
 *｛@code MBeanServer｝首先，设置
 *“locateExistingServerIfPossible”属性设置为“true”。
 *
 *@作者Rob Harrop
 *@作者于尔根·霍勒
 *@自1.2起
 *@请参阅#setLocateExistingServerIfPossible
 *@参见#locateBeanServer
 *@请参阅javax.management.MBeanServer
 *@参见javax.management.MBeanServerFactory#findMBeanServer
 *@参见javax.management.MBeanServerFactory#createMBeanServer
 *@参见javax.management.MBeanServerFactory#newMBeanServer
 *@参见MBeanServerConnectionFactoryBean
 *@请参阅ConnectorServerFactoryBean
 */
public class MBeanServerFactoryBean implements FactoryBean<MBeanServer>, InitializingBean, DisposableBean {

	protected final Log logger = LogFactory.getLog(getClass());

	private boolean locateExistingServerIfPossible = false;

	@Nullable
	private String agentId;

	@Nullable
	private String defaultDomain;

	private boolean registerWithFactory = true;

	@Nullable
	private MBeanServer server;

	private boolean newlyRegistered = false;


	/**
	 * Set whether the {@code MBeanServerFactoryBean} should attempt
	 * to locate a running {@code MBeanServer} before creating one.
	 * <p>Default is {@code false}.
	 */
	/**
	 *设置｛@code MBeanServerFactoryBean｝是否应尝试
	 *在创建运行中的｛@code MBeanServer｝之前，请先查找该服务器。
	 *＜p＞默认值为｛@code false｝。
	 */
	public void setLocateExistingServerIfPossible(boolean locateExistingServerIfPossible) {
		this.locateExistingServerIfPossible = locateExistingServerIfPossible;
	}

	/**
	 * Set the agent id of the {@code MBeanServer} to locate.
	 * <p>Default is none. If specified, this will result in an
	 * automatic attempt being made to locate the attendant MBeanServer,
	 * and (importantly) if said MBeanServer cannot be located no
	 * attempt will be made to create a new MBeanServer (and an
	 * MBeanServerNotFoundException will be thrown at resolution time).
	 * <p>Specifying the empty String indicates the platform MBeanServer.
	 * @see javax.management.MBeanServerFactory#findMBeanServer(String)
	 */
	/**
	 *设置要查找的｛@code MBeanServer｝的代理id。
	 *<p>默认值为none。如果指定，这将导致
	 *进行自动尝试以定位伴随的MBeanServer，
	 *并且（重要的是）如果不能找到所述MBeanServer
	 *将尝试创建一个新的MBeanServer（以及
	 *MBeanServerNotFoundException将在解析时引发）。
	 *<p>指定空字符串表示平台MBeanServer。
	 *@参见javax.management.MBeanServerFactory#findMBeanServer（字符串）
	 */
	public void setAgentId(String agentId) {
		this.agentId = agentId;
	}

	/**
	 * Set the default domain to be used by the {@code MBeanServer},
	 * to be passed to {@code MBeanServerFactory.createMBeanServer()}
	 * or {@code MBeanServerFactory.findMBeanServer()}.
	 * <p>Default is none.
	 * @see javax.management.MBeanServerFactory#createMBeanServer(String)
	 * @see javax.management.MBeanServerFactory#findMBeanServer(String)
	 */
	/**
	 *设置｛@code MBeanServer｝要使用的默认域，
	 *将传递给{@code MBeanServerFactory.createMBeanServer（）}
	 *或{@code MBeanServerFactory.findMBeanServer（）}。
	 *<p>默认值为none。
	 *@参见javax.management.MBeanServerFactory#createMBeanServer（字符串）
	 *@参见javax.management.MBeanServerFactory#findMBeanServer（字符串）
	 */
	public void setDefaultDomain(String defaultDomain) {
		this.defaultDomain = defaultDomain;
	}

	/**
	 * Set whether to register the {@code MBeanServer} with the
	 * {@code MBeanServerFactory}, making it available through
	 * {@code MBeanServerFactory.findMBeanServer()}.
	 * <p>Default is {@code true}.
	 * @see javax.management.MBeanServerFactory#createMBeanServer
	 * @see javax.management.MBeanServerFactory#findMBeanServer
	 */
	/**
	 *设置是否向
	 *｛@code MBeanServerFactory｝，通过
	 *｛@code MBeanServerFactory.findMBeanServer（）｝。
	 *＜p＞默认值为｛@code true｝。
	 *@参见javax.management.MBeanServerFactory#createMBeanServer
	 *@参见javax.management.MBeanServerFactory#findMBeanServer
	 */
	public void setRegisterWithFactory(boolean registerWithFactory) {
		this.registerWithFactory = registerWithFactory;
	}


	/**
	 * Creates the {@code MBeanServer} instance.
	 */
	/**
	 *创建｛@code MBeanServer｝实例。
	 */
	@Override
	public void afterPropertiesSet() throws MBeanServerNotFoundException {
		// Try to locate existing MBeanServer, if desired.
		// 如果需要，请尝试查找现有的MBeanServer。
		if (this.locateExistingServerIfPossible || this.agentId != null) {
			try {
				this.server = locateMBeanServer(this.agentId);
			}
			catch (MBeanServerNotFoundException ex) {
				// If agentId was specified, we were only supposed to locate that
				// 如果指定了agentId，我们只能找到
				// specific MBeanServer; so let's bail if we can't find it.
				// 特定的MBeanServer；如果找不到，我们就保释吧。
				if (this.agentId != null) {
					throw ex;
				}
				logger.debug("No existing MBeanServer found - creating new one");
			}
		}

		// Create a new MBeanServer and register it, if desired.
		// 如果需要，创建一个新的MBeanServer并进行注册。
		if (this.server == null) {
			this.server = createMBeanServer(this.defaultDomain, this.registerWithFactory);
			this.newlyRegistered = this.registerWithFactory;
		}
	}

	/**
	 * Attempt to locate an existing {@code MBeanServer}.
	 * Called if {@code locateExistingServerIfPossible} is set to {@code true}.
	 * <p>The default implementation attempts to find an {@code MBeanServer} using
	 * a standard lookup. Subclasses may override to add additional location logic.
	 * @param agentId the agent identifier of the MBeanServer to retrieve.
	 * If this parameter is {@code null}, all registered MBeanServers are
	 * considered.
	 * @return the {@code MBeanServer} if found
	 * @throws org.springframework.jmx.MBeanServerNotFoundException
	 * if no {@code MBeanServer} could be found
	 * @see #setLocateExistingServerIfPossible
	 * @see JmxUtils#locateMBeanServer(String)
	 * @see javax.management.MBeanServerFactory#findMBeanServer(String)
	 */
	/**
	 *尝试查找现有的｛@code MBeanServer｝。
	 *如果｛@code-locateExistingServerIfPossible｝设置为｛@code true｝，则调用。
	 *＜p＞默认实现尝试使用查找｛@code MBeanServer｝
	 *标准查找。子类可以重写以添加额外的位置逻辑。
	 *@param agentId要检索的MBeanServer的代理标识符。
	 *如果此参数为｛@code null｝，则所有注册的MBeanServers都是
	 *考虑。
	 *如果找到，@返回｛@code MBeanServer｝
	 *@throws org.springframework.jmx.MBeanServerNotFoundException
	 *如果找不到｛@code MBeanServer｝
	 *@请参阅#setLocateExistingServerIfPossible
	 *@see JmxUtils#locateBeanServer（字符串）
	 *@参见javax.management.MBeanServerFactory#findMBeanServer（字符串）
	 */
	protected MBeanServer locateMBeanServer(@Nullable String agentId) throws MBeanServerNotFoundException {
		return JmxUtils.locateMBeanServer(agentId);
	}

	/**
	 * Create a new {@code MBeanServer} instance and register it with the
	 * {@code MBeanServerFactory}, if desired.
	 * @param defaultDomain the default domain, or {@code null} if none
	 * @param registerWithFactory whether to register the {@code MBeanServer}
	 * with the {@code MBeanServerFactory}
	 * @see javax.management.MBeanServerFactory#createMBeanServer
	 * @see javax.management.MBeanServerFactory#newMBeanServer
	 */
	/**
	 *创建一个新的｛@code MBeanServer｝实例，并使用
	 *｛@code MBeanServerFactory｝，如果需要。
	 *@param defaultDomain默认域，或者｛@code null｝如果没有
	 *@param registerWithFactory是否注册｛@code MBeanServer｝
	 *使用｛@code MBeanServerFactory｝
	 *@参见javax.management.MBeanServerFactory#createMBeanServer
	 *@参见javax.management.MBeanServerFactory#newMBeanServer
	 */
	protected MBeanServer createMBeanServer(@Nullable String defaultDomain, boolean registerWithFactory) {
		if (registerWithFactory) {
			return MBeanServerFactory.createMBeanServer(defaultDomain);
		}
		else {
			return MBeanServerFactory.newMBeanServer(defaultDomain);
		}
	}


	@Override
	@Nullable
	public MBeanServer getObject() {
		return this.server;
	}

	@Override
	public Class<? extends MBeanServer> getObjectType() {
		return (this.server != null ? this.server.getClass() : MBeanServer.class);
	}

	@Override
	public boolean isSingleton() {
		return true;
	}


	/**
	 * Unregisters the {@code MBeanServer} instance, if necessary.
	 */
	/**
	 *如有必要，请注销｛@code MBeanServer｝实例。
	 */
	@Override
	public void destroy() {
		if (this.newlyRegistered) {
			MBeanServerFactory.releaseMBeanServer(this.server);
		}
	}

}
